package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.etsy.android.grid.StaggeredGridView;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.wephone.Student.R;

import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.GroupInfoDetailResponse;
import com.wephone.Student.bean.GroupOnlineListResponse;
import com.wephone.Student.bean.GroupResponse;
import com.wephone.Student.bean.GroupsListResponse;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.MyLocationInfo;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.RoundImageView;
import com.wephone.Student.util.Util;
import com.wephone.Student.util.Utils;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;


public class AllRecGroupsActivity extends BaseActivity {
	private String uid;
	private TextView top_bar_title;
	private ArrayList<GroupInfo> groups = new ArrayList<GroupInfo>();//群列表
	private Button add_group;
	private PullToRefreshView pullToRefreshListView10;
	private StaggeredGridView gridView10;
	private GridViewAdapter adapter10;
	private List<GroupInfo> results10 = new ArrayList<GroupInfo>();
	
	private MyResponseHandler getHandler2(){
		MyResponseHandler handler = new MyResponseHandler(AllRecGroupsActivity.this,GroupOnlineListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				findViewById(R.id.progressBar).setVisibility(View.GONE);
				System.out.println("---------Success:"+getDataSuccess);
				if(getDataSuccess){
					GroupOnlineListResponse res = (GroupOnlineListResponse)response;
//					
					if(adapter10.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter10.hasMore = false;
					}else{
						adapter10.pageIdx++;
					}
					System.out.println("---------Groups:"+res.getTotalPage());
					//results2.clear();
					for(GroupInfo infoData:res.getData()){
						results10.add(infoData);
					}
					adapter10.notifyDataSetChanged();
					System.out.println("---------Groups1:"+res.getTotalPage());
				}
			}
		};
		return handler;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rec_groups);
		
		init();
		
	}
	
	private void init(){
		
		top_bar_title = (TextView)findViewById(R.id.top_bar_title);
		add_group = (Button)findViewById(R.id.add_group);
		add_group.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startActivity(new Intent(getApplicationContext(),NewGroupActivity1.class));
			}
		});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		gridView10 = (StaggeredGridView)findViewById(R.id.gridview10);
		adapter10 = new GridViewAdapter();
		adapter10.setData(results10);
		gridView10.setAdapter(adapter10);
		gridView10.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupData", results10.get(arg2));
				startActivity(new Intent(getApplicationContext(),GroupInfoDetailActivity.class).putExtras(bundle));
			}});
		
		pullToRefreshListView10 = (PullToRefreshView)findViewById(R.id.pull_refresh_listview10);
		pullToRefreshListView10.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			@Override
			public void onHeaderRefresh(PullToRefreshView view) {
				adapter10.hasMore = true;
				adapter10.pageIdx = 1;
				results10.clear();
				adapter10.notifyDataSetChanged();
				
				RequestParams params = new RequestParams();
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				
				HttpClient.getInstance().get(Constants.API_REC_CHART_LIST_URL, params, getHandler2());
			}
		});
		pullToRefreshListView10.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			@Override
			public void onFooterRefresh(PullToRefreshView view) {
				if(!adapter10.hasMore){
					pullToRefreshListView10.onFooterRefreshComplete();
					return;
				}
				RequestParams params = new RequestParams();
				params.put("Page", ""+adapter10.pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				
				params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				HttpClient.getInstance().get(Constants.API_REC_CHART_LIST_URL, params, getHandler2());
			}
		});
			//refresh();
	}	
	
	private void refresh(){
		findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
		groups.clear();
		RequestParams params2 = new RequestParams();
		params2.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
		params2.put("Page", "1");
		params2.put("PageSize", ""+Constants.PAGE_SIZE);
		HttpClient.getInstance().get(Constants.API_REC_CHART_LIST_URL, params2, getHandler2());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		refresh();
	}
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.default_user_logo)
    .showImageOnFail(R.drawable.default_user_logo)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
//    .displayer(new RoundedBitmapDisplayer(1000))
    .build();
	
	private class GridViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		private Gson gson = new Gson();
		private List<GroupInfo> datas;
		
		public void setData(List<GroupInfo> data){
			this.datas = data;
		}
		
		@Override
		public int getCount() {
			System.out.println("results2:"+datas.size());
			return datas.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//System.out.println("getView111:");
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.group_view_item, null);
			}
			
			GroupInfo groupData = datas.get(position);
			System.out.println("getView:"+groupData.getName());
			TextView itemName = (TextView)convertView.findViewById(R.id.groupName);
			itemName.setText(groupData.getName());
			TextView itemDesc = (TextView)convertView.findViewById(R.id.groupDesc);
			itemDesc.setText(groupData.getContent());
			
			TextView groupCountry = (TextView)convertView.findViewById(R.id.groupCountry);
			groupCountry.setText(groupData.getClog());
			TextView groupNum = (TextView)convertView.findViewById(R.id.groupNum);
			groupNum.setText(groupData.getNownum()+"/"+groupData.getMaxnum());
			
			final ImageView item_pic = (ImageView)convertView.findViewById(R.id.group_pic);
			
			ImageView is_rec = (ImageView)convertView.findViewById(R.id.is_rec);
			
			if(groupData.getIsrec().equals("0")){
				is_rec.setVisibility(View.GONE);
			}else{
				is_rec.setVisibility(View.VISIBLE);
			}
			
			
			ImageView now_num_line = (ImageView)convertView.findViewById(R.id.now_num_line);
			
			float real_width = Util.getScreenWidth(getApplicationContext())*Integer.parseInt(groupData.getNownum())/Integer.parseInt(groupData.getMaxnum());
			
			now_num_line.getLayoutParams().width = (int)Util.convertDpToPixel(real_width*2, getApplicationContext());
			
			Resources res = getResources();  
		    Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.big_logo);  
			final Bitmap tempBitmap1 = Utils.getFixedBitMap(bmp,getApplicationContext(),2);
			
			if(!TextUtils.isEmpty(groupData.getPic())){
				//String endStr = groupData.getPic().substring(groupData.getPic().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+groupData.getPic(),item_pic, options,new ImageLoadingListener() {
					
					@Override
					public void onLoadingCancelled(String arg0, View arg1) {
						// TODO Auto-generated method stub
						
					}
					@Override
					public void onLoadingComplete(String arg0, View arg1,
							Bitmap arg2) {
						// TODO Auto-generated method stub
						Bitmap tempBitmap = Utils.getFixedBitMap(arg2,getApplicationContext(),2);
						if(tempBitmap != null) {
							item_pic.setImageBitmap(tempBitmap);
						}
					}

					@Override
					public void onLoadingFailed(String arg0, View arg1,
							FailReason arg2) {
						// TODO Auto-generated method stub
						if(tempBitmap1 != null) {
							item_pic.setImageBitmap(tempBitmap1);
						}
					}

					@Override
					public void onLoadingStarted(String arg0, View arg1) {
						// TODO Auto-generated method stub
						
					}
				});		
			}else{
				
				if(tempBitmap1 != null) {
					item_pic.setImageBitmap(tempBitmap1);
				}
			}
			return convertView;
		}		
	}
}
